package com.nemodynamic.cattivial;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import net.sourceforge.jeval.Evaluator;

import android.content.Context;
import android.media.MediaPlayer;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.TextView;

import com.nemodynamic.cattivial.UIElement.CattivialFaceItemView;
import com.nemodynamic.cattivial.UIElement.CattivialFoodItemView;
import com.nemodynamic.cattivial.beansElement.CattivialFaceItem;
import com.nemodynamic.cattivial.beansElement.CattivialFoodItem;
import com.nemodynamic.cattivial.gamecenter.LiderBoardUtils;
import com.nemodynamic.cattivial.utils.DLog;

public class GameManager {
	private static final String SIGLEMATCH = "SingleMatch";
	private static final String TAG = "GameManager";
	private boolean isStarted;
	private boolean isInit = true;
	private int itemNumber = 0;
	private int questionNumber = 0;
	private static GameManager gameManager;
	private ViewGroup gameContainer;
	private TextView[] resultsTextViews;
	private TextView question;
	private Context context;
	private int level;
	private List<CattivialFoodItem> foods;
	private List<CattivialFaceItem> faces;
	private MediaPlayer mediaPlayer;

	private GameManager() {
	}

	public static synchronized GameManager getNewInstance(Context context, int level, ViewGroup gameContainer, TextView[] resultsTextViews, TextView question) {
		if (gameManager != null && (gameManager.isStarted || !gameManager.isInit)) {
			DLog.i(TAG, "Another game is currently active!");
			return null;
		} else {

			if (gameManager == null) {
				gameManager = new GameManager();
			}
			gameManager.isInit = false;
			gameManager.isStarted = false;
			gameManager.gameContainer = gameContainer;
			gameManager.itemNumber = gameManager.getInitialNumberItem(level);
			gameManager.context = context;
			gameManager.level = level;
			gameManager.resultsTextViews = resultsTextViews;
			gameManager.question = question;
			gameManager.foods = new ArrayList<CattivialFoodItem>();
			gameManager.faces = new ArrayList<CattivialFaceItem>();
			gameManager.cretaeFoods(level, gameManager.foods);

			return gameManager;
		}
	}

	public static synchronized GameManager getCurrentInstance() {
		return gameManager;
	}

	public void setGameMusic(int soundResource) {
		if (GameManager.gameManager != null) {
			gameManager.mediaPlayer = MediaPlayer.create(context, soundResource);
			gameManager.mediaPlayer.setLooping(true);
			gameManager.mediaPlayer.setScreenOnWhilePlaying(true);
		}
	}

	public void playMusic() {
		if (gameManager.mediaPlayer != null && !gameManager.mediaPlayer.isPlaying()) {
			gameManager.mediaPlayer.start();
		}
	}

	public void stopMusic() {
		if (gameManager.mediaPlayer != null && gameManager.mediaPlayer.isPlaying()) {
			gameManager.mediaPlayer.stop();
		}
	}

	public void pauseMusic() {
		if (gameManager.mediaPlayer != null && gameManager.mediaPlayer.isPlaying()) {
			gameManager.mediaPlayer.pause();
		}
	}

	public void resumeMusic() {
		if (gameManager.mediaPlayer != null && !gameManager.mediaPlayer.isPlaying()) {
			gameManager.mediaPlayer.start();
		}
	}

	public void removeFaceItem(final View v) {
		if (gameManager.isStarted) {
			gameManager.itemNumber--;
			gameManager.gameContainer.post(new Runnable() {

				@Override
				public void run() {
					DLog.i(TAG, "Face item removed!" + v);
					gameManager.gameContainer.removeView(v);
					DLog.i(TAG, "Item number =" + gameManager.itemNumber);
				}
			});

		} else {
			DLog.i(TAG, "Game item not removed, no game active!");
		}
	}

	public void addFaceItem(final CattivialFaceItemView v) {
		v.setFoods(gameManager.foods);
		CattivialFaceItem cattivialFaceItem = ((CattivialFaceItemView) v).getFaceItem();
		gameManager.faces.add(cattivialFaceItem);
		gameManager.itemNumber = gameManager.faces.size();
		gameManager.gameContainer.addView(v);
		DLog.i(TAG, "Face item added! Faces Size is = " + gameManager.faces.size());
	}

	public void addFoodItem(final View v) {
		gameManager.gameContainer.addView(v);
		DLog.i(TAG, "Food item added!");
	}

	public int getFaceItemsSize() {
		return gameManager.itemNumber;
	}

	public final void startGame() {
		if (gameManager.isStarted == false) {
			DLog.i(TAG, "Game Started");
			gameManager.isStarted = true;
			gameManager.itemNumber = gameManager.faces.size();
			nextQuestion();
			gameManager.playMusic();
			CattivialFaceItemView.start();
			CattivialFoodItemView.start();
			System.out.println(gameManager.foods);
		} else {
			DLog.i(TAG, "Another game is currently active!");
		}

	}
	public final void stopGame() {
		stopGame(null);
	}
	public final void stopGame(String score) {

		if (gameManager.isStarted == true) {
			DLog.i(TAG, "Game Stopped");
			gameManager.isInit = true;
			gameManager.isStarted = false;
			gameManager.itemNumber = 0;
			gameManager.stopMusic();
			CattivialFaceItemView.stop();
			CattivialFoodItemView.stop();
			gameManager.gameContainer.post(new Runnable() {

				@Override
				public void run() {
					gameManager.gameContainer.removeAllViews();

				}
			});
			gameManager.faces.clear();
			gameManager.foods.clear();
			if (score != null) {
				LiderBoardUtils.setScore(SIGLEMATCH, SIGLEMATCH, "123", "Pietro Leggero", Integer.parseInt(score));
			}
		} else {
			DLog.i(TAG, "No game is currently active!");
		}

	}

	public boolean isGameStarted() {
		return gameManager.isStarted;
	}

	private void cretaeFoods(int level, List<CattivialFoodItem> foodList) {

		gameManager.addFoodItem(createFoodItemView(R.drawable.cherry, foodList));
		gameManager.addFoodItem(createFoodItemView(R.drawable.cocktail, foodList));
		gameManager.addFoodItem(createFoodItemView(R.drawable.cupcake, foodList));
		gameManager.addFoodItem(createFoodItemView(R.drawable.cherry, foodList));
		gameManager.addFoodItem(createFoodItemView(R.drawable.cocktail, foodList));
		gameManager.addFoodItem(createFoodItemView(R.drawable.cupcake, foodList));
		gameManager.addFoodItem(createFoodItemView(R.drawable.cherry, foodList));
		gameManager.addFoodItem(createFoodItemView(R.drawable.cocktail, foodList));
		gameManager.addFoodItem(createFoodItemView(R.drawable.cupcake, foodList));
	}

	private CattivialFoodItemView createFoodItemView(int resource, List<CattivialFoodItem> foodList) {
		Random random = new Random();
		double xRamdom = random.nextFloat();
		double yRandom = random.nextFloat();
		int x = (int) (gameManager.gameContainer.getWidth() * xRamdom);
		int y = (int) (gameManager.gameContainer.getHeight() * yRandom);
		if (x > gameManager.gameContainer.getWidth() - 250) {
			x -= 250;
		} else if (x < 250) {
			x += 250;
		}
		if (y > gameManager.gameContainer.getHeight() - 250) {
			y -= 250;
		} else if (y < 250) {
			y += 250;
		}

		CattivialFoodItem cattivialFoodItem = new CattivialFoodItem(resource, 5, 20, x, y, 250, 250);
		foodList.add(cattivialFoodItem);
		DLog.i(TAG, "A new food i created at position x:" + x + " y:" + y);
		return new CattivialFoodItemView(gameManager.context, cattivialFoodItem);
	}

	private int getInitialNumberItem(int level) {
		return level;
	}

	public void nextQuestion() {
		DLog.i(TAG, "Item number =" + gameManager.itemNumber);
		DLog.i(TAG, "Faces Size =" + gameManager.faces.size());
		if (gameManager.itemNumber > 0) {
			DLog.i(TAG, "Item number >0");
			int randomFace = new Random().nextInt(gameManager.faces.size());
			CattivialFaceItem faceItem = null;

			for (int index = randomFace; index < gameManager.faces.size(); index++) {
				DLog.i(TAG, "Index" + index);
				CattivialFaceItem faceItemTmp = gameManager.faces.get(index);
				if (!faceItemTmp.isConsumed() && !faceItemTmp.isActive()) {
					faceItem = faceItemTmp;
					break;
				}
			}

			if (faceItem == null) {
				for (int index = randomFace - 1; index >= 0; index--) {
					DLog.i(TAG, "Index" + index);
					CattivialFaceItem faceItemTmp = gameManager.faces.get(index);
					if (!faceItemTmp.isConsumed() && !faceItemTmp.isActive()) {
						faceItem = faceItemTmp;
						break;
					}
				}
			}

			try {
				faceItem.setConsumed(true);
				faceItem.setActive(true);
				DLog.i(TAG, "Attivata " + faceItem);
				final int[] results = faceItem.getResults();

				if (gameManager.resultsTextViews[0] != null) {
					gameManager.resultsTextViews[0].setText("" + results[0]); // TODO}
				}

				if (gameManager.resultsTextViews[0] != null) {
					gameManager.resultsTextViews[1].setText("" + results[1]);
				}

				if (gameManager.resultsTextViews[0] != null) {
					gameManager.resultsTextViews[2].setText("" + results[2]);
				}

				Animation questionIn = AnimationUtils.loadAnimation(context, R.anim.question_in);
				questionIn.setFillAfter(true);
				questionIn.setAnimationListener(new AnimationListener() {

					@Override
					public void onAnimationStart(Animation animation) {
						gameManager.question.setVisibility(View.VISIBLE);

					}

					@Override
					public void onAnimationRepeat(Animation animation) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onAnimationEnd(Animation animation) {
						Animation questionout = AnimationUtils.loadAnimation(context, R.anim.question_out);
						questionout.setFillAfter(true);
						gameManager.question.startAnimation(questionout);

					}
				});

				gameManager.question.setText(faceItem.getQuestion());
				gameManager.question.startAnimation(questionIn);

			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			DLog.i(TAG, "Item number =0");

			for (CattivialFaceItem faceItem : gameManager.faces) {
				if (!faceItem.isConsumed()) {
					faceItem.setConsumed(true);
					faceItem.setActive(true);
					final int[] results = faceItem.getResults();
					try {

						if (gameManager.resultsTextViews[0] != null) {
							System.out.println(gameManager);
							System.out.println(results[0]);
							gameManager.resultsTextViews[0].setText("" + results[0]);
						}

						if (gameManager.resultsTextViews[0] != null) {
							gameManager.resultsTextViews[1].setText("" + results[1]);
						}

						if (gameManager.resultsTextViews[0] != null) {
							gameManager.resultsTextViews[2].setText("" + results[2]);
						}

						if (gameManager.resultsTextViews[0] != null) {
							gameManager.question.setText(faceItem.getQuestion());
						}

						break;
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

}
